import ajax from '@/uni_modules/u-ajax/js_sdk/index.js'
import cache from '@/utils/cache.js'
import appConfig from '@/config/config.app.js'
import configRouter from '@/config/config.router.js'

let refreshing = false
const requestQueue = []

// 创建请求实例
const instance = ajax.create({
    // 初始配置
    baseURL: appConfig.baseURL, //请求根地址

    // 请求拦截器
    adapter(config) {
        if (config.method === 'UPLOAD') {
            return new Promise((resolve, reject) => {
                const uploadTask = uni.uploadFile({
                    url: config.url, //仅为示例，非真实的接口地址
                    ...config.data,
                    header: {
                        ...config.header,
                    },
                    complete: (result) => {
                        try {
                            result.data = JSON.parse(result.data)
                        } catch (error) {}
                        resolve({ config, ...result })
                    },
                })
                config.fetcher?.resolve(uploadTask)
            })
        }
        return ajax.defaults.adapter(config) // 默认的适配器,必须要返回，否则就请求不到结果了。
    },
})

// 添加请求拦截器
instance.interceptors.request.use(
    (config) => {
        // 显示 loading
        uni.showLoading({ title: '加载中...' })

        config.header = {
            ...config.header,
            authorization: cache.get('token'),
        }
        return config
    },
    (error) => {
        // 对请求错误做些什么
        console.error('Request Error:', error)
        return Promise.reject(error)
    },
)

// 添加响应拦截器
instance.interceptors.response.use(
    async (response) => {
        // 关闭 loading
        uni.hideLoading()

        const { config, data: res } = response
        const { code, msg } = res
        if (code === 200) {
            return res
        }
        if (code === 401 && !config.url.includes('/token')) {
            return refreshToken(config)
        }
        handleResponseError(code, msg)
        return Promise.reject(response)
    },
    (error) => {
        // 关闭 loading
        uni.hideLoading()

        handleRequestError(error)
        return Promise.reject(error)
    },
)

async function refreshToken(config) {
    if (refreshing) {
        return new Promise((resolve) => requestQueue.push({ config, resolve }))
    }
    refreshing = true

    try {
        const res = await instance.get(`/token/${cache.get('refreshToken')}`)
        if (res.code === 200) {
            cache.set('token', res.data.token || null)
            cache.set('refreshToken', res.data.refreshToken || null)
            const results = await Promise.all(requestQueue.map((item) => instance(item.config)))
            requestQueue.forEach(({ config, resolve }) => {
                resolve(results.find((result) => result.config === config))
            })
            requestQueue.length = 0
            return instance(config)
        } else {
            clearCacheAndRedirectToLogin()
            throw new Error(res.code, ': refreshToken过期，跳转登录页')
        }
    } catch (error) {
        console.error('Token refresh failed:', error)
        clearCacheAndRedirectToLogin()
        return Promise.reject({ code: 401, msg: 'Token refresh failed.', error })
    } finally {
        refreshing = false
        // 关闭 loading
        uni.hideLoading()
    }
}

// 清空缓存并跳转到登录页
function clearCacheAndRedirectToLogin() {
    cache.clear() // 清空缓存
    console.log('缓存已清空，跳转到登录页')
    const pages = getCurrentPages()
    let path = pages[pages.length - 1]?.$page?.fullPath || configRouter.homePage
    uni.redirectTo({
        url: `${configRouter.loginPage}?redirectUrl=${encodeURIComponent(path)}`,
    })
}

// 错误处理
function handleResponseError(code, msg) {
    switch (code) {
        case 500:
            uni.showToast({ title: msg ?? '服务器错误', icon: 'none', duration: 3000 })
            break
        default:
            console.log('请求失败', msg)
    }
}
function handleRequestError(error) {
    console.log('error', error)
}

export default instance
